package com.feonix.redis.serializer;

import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 如无特殊情况，最好key 和value都使用string类型，把value转换为json字符串存储即可
 * 
 * @author Administrator
 *
 */
public class KeyStringValueObject {

	@SuppressWarnings({ "unchecked" })
	@Test
	public void test() {

		ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(
				"spring-context-jedis.xml");

		RedisTemplate<String, Object> redisTemplate = applicationContext.getBean("jedisTemplate", RedisTemplate.class);
		Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(
				Object.class);
		ObjectMapper objectMapper = new ObjectMapper();
		objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
		objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
		jackson2JsonRedisSerializer.setObjectMapper(objectMapper);

		redisTemplate.setKeySerializer(jackson2JsonRedisSerializer);
		redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
		redisTemplate.setHashKeySerializer(jackson2JsonRedisSerializer);
		redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);

		redisTemplate.opsForValue().set("aa", "bb");
		System.out.println("=============1" + redisTemplate.opsForValue().get("aa"));

		Student stu = new Student();
		stu.setName("伟哥");
		stu.setAge(18);
		stu.setOrdNo("66");
		redisTemplate.opsForValue().set("weige", stu);
		System.out.println("=============2" + ((Student) redisTemplate.opsForValue().get("weige")).getName());

	}

}

class Student {
	private String name;
	private Integer age;
	private String ordNo;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	public String getOrdNo() {
		return ordNo;
	}

	public void setOrdNo(String ordNo) {
		this.ordNo = ordNo;
	}

}
